#include <stdio.h>
#include <stdlib.h>
#include <QDebug>
#include <QTextStream>
#include <QDateTime>
#include <QFile>
#include <QMutex>

#include "logger.h"

int Logger::max_log_file_size = 1024 * 1024;

QString Logger::log_file_name = "debug.log";

void Logger::install_logger(int log_file_size, QString log_file_name)
{
    Logger::max_log_file_size = log_file_size;
    Logger::log_file_name = log_file_name;

    qInstallMessageHandler(log_message_handler);
}

void Logger::log_message_handler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("[Debug]");
        break;
    case QtWarningMsg:
        text = QString("[Warning]");
        break;
    case QtCriticalMsg:
        text = QString("[Critical]");
        break;
    case QtFatalMsg:
        text = QString("[Fatal]");
    }

    QString context_info = QString("[%1:%2]").arg(QString(context.file)).arg(context.line);
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz");
    QString current_date = QString("%1").arg(current_date_time);
    QString message = QString("%1 %2 %3 %4").arg(current_date).arg(text).arg(context_info).arg(msg);

    QFile file(log_file_name);
    if (file.size() > max_log_file_size) {
        file.remove();
    }
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream << message << "\r\n";
    file.flush();
    file.close();

    mutex.unlock();
}



